package User;

import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class UserRegister { // 注册数据处理者
    Connection connection = null;
    PreparedStatement presql; // 预处理对象

    public UserRegister() throws SQLException, ClassNotFoundException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://mysql.sqlpub.com:3306/ai_text?useSSL=false&serverTimezone=UTC";
            String username = "root_jin";
            String password = "PYdB6vd981yvuLhD";
            connection = DriverManager.getConnection(url, username, password);
            //System.out.println("数据库连接成功");
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "数据库连接失败，请联系管理员", "提示", JOptionPane.WARNING_MESSAGE);
            throw e; // 抛出异常以通知调用者连接失败
        }
    }

    public void writeRegister(Register register) {
        int flag = 0;
        try {
            String sql = "INSERT INTO users (userName, password) VALUES (?, ?)"; // 假设数据库表字段名为 userName 和 password
            presql = connection.prepareStatement(sql);
            presql.setString(1, register.getUserName());
            presql.setString(2, register.getPassword());
            flag = presql.executeUpdate(); // 成功插入时返回1

            if (flag != 0) {
                JOptionPane.showMessageDialog(null, "注册成功");
            } else {
                JOptionPane.showMessageDialog(null, "注册失败，请稍后重试", "提示", JOptionPane.WARNING_MESSAGE);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "注册失败，可能是因为用户名已存在！", "警告", JOptionPane.WARNING_MESSAGE);
        } finally {
            try {
                if (presql != null) presql.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (connection != null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        System.out.println("注册操作结束，受影响行数：" + flag);
    }
}
